﻿using System;
using BoldBrick.Core.Logging;
using Microsoft.SharePoint;

namespace BoldBrick.SharePoint.CommonControls.Extensions
{
	public static class SPUserCollectionEx
	{
		private static readonly ILogger log = Logger.GetLogger(typeof (SPUserCollectionEx));
		
		/// <summary>
		/// Gets user by id (Safe method), returns null is user is not found
		/// </summary>
		/// <param name="users">Users collection</param>
		/// <param name="id">ID of the user</param>
		/// <returns>Returns user by id if the user exists, otherwise returns null</returns>
		public static SPUser TryGetUserById(this SPUserCollection users, int id)
		{
			try
			{
				SPUser user = users.GetByID(id);
				return user;
			}
			catch (Exception ex)
			{
				log.Write(LogLevel.Warn, ex, "Get user failed");
			}
			return null;
		}
		
		/// <summary>
		/// Gets user by login name (Safe method), returns null is user is not found
		/// </summary>
		/// <param name="users">Users collection</param>
		/// <param name="loginName">Login name of the user</param>
		/// <returns>Returns user by login name if the user exists, otherwise returns null</returns>
		public static SPUser TryGetUserByLoginName(this SPUserCollection users, string loginName)
		{
			try
			{
				SPUser user = users[loginName];
				return user;
			}
			catch (Exception ex)
			{
				log.Write(LogLevel.Warn, ex, "Get user failed");
			}
			return null;
		}
	}
}
